<template>
	<view>
		<signup-card v-if="detailsData" :examData="detailsData"></signup-card>

		<view class="container">

			<u-line color="black" />
			<!-- 公共表单 -->
			<!-- <public-form :form.sync="publicForm"></public-form> -->
			<u-form class="u-form-list" label-width="100px">
				<div v-for="(item, idx) of publicForm" :key="idx">
					<!-- 文本 -->
					<u-form-item v-if="item.type === 1" :label="item.ndsib">
						<u-input v-model="item.value"></u-input>
					</u-form-item>
					
					<!-- 单选 -->
					<u-form-item v-else-if="item.type === 2" :label="item.ndsib">
						<u-radio-group v-model="item.value">
							<u-radio v-for="(items, idxs) in item.optn" :name="items.value" :key="idxs">{{ items.key }}</u-radio>
						</u-radio-group>
					</u-form-item>
					
					<!-- 多选 -->
					<u-form-item v-else-if="item.type === 3" :label="item.ndsib">
						<u-checkbox-group @change="checkboxGroupChangePublic($event,idx)">
							<u-checkbox v-model="items.checked" v-for="(items, idxs) of item.optn" :name="items.value" :key="idxs">{{items.key}}</u-checkbox>
						</u-checkbox-group>
					</u-form-item>
					
					<!-- 下拉选项 -->
					<u-form-item v-else-if="item.type === 4" :label="item.ndsib">
					
						<u-input v-model="item.label" type="select" @click="showSelectPublic(idx)" />
						<u-select v-model="item.isShow" :list="item.optn" label-name="key" @confirm="confirmPublic($event,idx)"></u-select>
					</u-form-item>
					
					<!-- 上传文件 -->
					<u-form-item v-else-if="item.type === 5" :label="item.ndsib">
						<!-- <upload :idPic.sync="item.value"></upload> -->
						
						<u-upload :ref="item.id" action="#" :auto-upload="false" max-count="1" :file-list="[{url:item.value}]" :max-size="1 * 1024 * 1024" :show-progress="false" :size-type="['compressed']" @on-list-change="onListChange($event,item,idx)"></u-upload>
					</u-form-item>
					
					<!-- 日期 -->
					<u-form-item v-else-if="item.type === 6" :label="item.ndsib">
					
						<u-input v-model="item.value" type="select" @click="showDatePickerPublic(idx)" />
						<u-picker v-model="item.isShow" mode="time" :params="{year: true,month: true,day: true}" @confirm="changeDayPublic($event,idx)"></u-picker>
					</u-form-item>
					
					<!-- 多行文本 -->
					<u-form-item v-else-if="item.type === 7" :label="item.ndsib">
						<u-input type="textarea" v-model="item.value"></u-input>
					</u-form-item>
				</div>
			</u-form>

			<u-line color="black" />
			<!-- 特殊表单 -->
			<!-- <special-form :form.sync="specialForm"></special-form> -->
			<u-form class="u-form-list" label-width="100px">
				<div v-for="(item, idx) of specialForm" :key="idx">
					<!-- 文本 -->
					<u-form-item v-if="item.type === 1" :label="item.ndsib">
						<u-input v-model="item.value"></u-input>
					</u-form-item>

					<!-- 单选 -->
					<u-form-item v-else-if="item.type === 2" :label="item.ndsib">
						<u-radio-group v-model="item.value">
							<u-radio v-for="(items, idxs) in item.optn" :name="items.value" :key="idxs">{{ items.key }}</u-radio>
						</u-radio-group>
					</u-form-item>

					<!-- 多选 -->
					<u-form-item v-else-if="item.type === 3" :label="item.ndsib">
						<u-checkbox-group @change="checkboxGroupChange($event,idx)">
							<u-checkbox v-model="items.checked" v-for="(items, idxs) of item.optn" :name="items.value" :key="idxs">{{items.key}}</u-checkbox>
						</u-checkbox-group>
					</u-form-item>

					<!-- 下拉选项 -->
					<u-form-item v-else-if="item.type === 4" :label="item.ndsib">

						<u-input v-model="item.label" type="select" @click="showSelect(idx)" />
						<u-select v-model="item.isShow" :list="item.optn" label-name="key" @confirm="confirm($event,idx)"></u-select>
					</u-form-item>

					<!-- 上传文件 -->
					<u-form-item v-else-if="item.type === 5" :label="item.ndsib">
						<upload :idPic.sync="item.value"></upload>
					</u-form-item>

					<!-- 日期 -->
					<u-form-item v-else-if="item.type === 6" :label="item.ndsib">

						<u-input v-model="item.value" type="select" @click="showDatePicker(idx)" />
						<u-picker v-model="item.isShow" mode="time" :params="{year: true,month: true,day: true}" @confirm="changeDay($event,idx)"></u-picker>
					</u-form-item>

					<!-- 多行文本 -->
					<u-form-item v-else-if="item.type === 7" :label="item.ndsib">
						<u-input type="textarea" v-model="item.value"></u-input>
					</u-form-item>
				</div>
			</u-form>


			<div class="submit">
				<u-button type="primary" @click="codeShowFn">提交</u-button>
			</div>
		</view>

		<!-- 提示弹窗 -->
		<u-modal v-model="dialogVisible">
			<span>请输入:</span>
			<span v-for="(item, idx) of errorArr" :key="idx">{{ item }}、</span>
		</u-modal>

		<!-- 验证码弹窗 -->
		<u-modal v-model="codeShow" @confirm="submit" :async-close="true" :content-style="{'padding': '0 20rpx','box-sizing': 'border-box'}">
			<u-form :model="codeForm" ref="codeForm">
				<u-form-item label="验证码" prop="code" label-width="120">
					<u-input v-model="codeForm.code" />

					<u-button type="success" slot="right" size="mini" @click="sendCode">{{timeHandlerBool ? '验证码' : time+'秒'}}</u-button>
				</u-form-item>
			</u-form>
		</u-modal>

		<u-toast ref="uToast" />

		<wyb-loading ref="loading" />
	</view>
</template>

<script>
	import {
		getFrom
	} from "@/api/apiList/exam.js";

	import {
		getExaminee,
		signupCaptcha,
		update
	} from "@/api/apiList/user.js";

	import {
		save
	} from "@/api/apiList/exam.js";
	
	import {
		getBase64
	} from "@/utils/getBase64.js"

	import upload from "@/components/upload.vue"
	import wybLoading from '@/components/wyb-loading/wyb-loading.vue'
	import signupCard from "@/components/signupCard.vue"
	
	import {
		createNamespacedHelpers
	} from 'vuex'
	const {
		mapMutations
	} = createNamespacedHelpers('userInfoModule')

	export default {
		components: {
			wybLoading,
			signupCard,
			upload
		},
		data() {
			return {
				form: "", //动态表单数据
				userData: {}, //静态表单
				formData: {}, //动态表单
				isEdit: false, //是否为编辑状态
				loading: false,
				dialogVisible: false,
				errorArr: [],
				submitLoading: false, //提交按钮loading
				detailsData: "", //考试详细数据
				specialForm: [],
				codeShow: false,
				codeForm: {
					code: ""
				},
				codeFormRules: {
					code: [{
						required: true,
						message: '请输入短信验证码',
						trigger: 'blur'
					}]
				},
				time: 60, //倒计时
				timeHandlerBool: true,
				timeHandler: "",
				publicForm: "",
				specialForm: ""
			};
		},
		methods: {
			...mapMutations(["UPDATE_USER_INFO"]),
			async API_getFrom(eid) {
				//考试表格接口
				let result = {
					param: {
						eid,
					},
				};
				return await getFrom(result);
			},
			async API_getExaminee() {
				//获取个人信息接口
				return await getExaminee();
			},
			async API_save(data) {
				//报考接口
				let result = {
					data,
					param: {
						code: this.codeForm.code
					}
				};
				return await save(result);
			},
			async API_update(data) { //编辑个人信息
				let result = {
					data, //个人信息
				};
				return await update(result)
			},
			formOptn(arr) {
				//格式化选项
				return arr.map((item) => {
					if (item.type == 2 || item.type == 3) {
						let optnArr = item.optn.split(",");
						let optns = [];
						optnArr.forEach((items) => {
							let [value, key] = items.split("-");
							optns.push({
								key: key,
								value: Number(value),
								checked: false
							});
						});
						item.optn = optns;
					}
					if (item.type == 4) {
						let optnArr = item.optn.split(",");
						let optns = [];
						optnArr.forEach((items) => {
							let [value, key] = items.split("-");
							optns.push({
								key: key,
								value: value,
							});
						});
						item.optn = optns;
					}
					if (item.type == 3) { //多选
						//多选
						item.value = [];
					} else {
						item.value = "";
					}
					if (item.type === 4) { //列选择器
						item.isShow = false
						item.label = ""
					}
					if (item.type === 6) { //日期选择器
						item.isShow = false
					}
					return item;
				});
			},
			filter(form, userData) {
				//对比过滤(form特殊表单,userData公共表单)
				let sForm = form.filter((item) => {
					//过滤出公共数据
					if (item.crer) {
						return item;
					}
				});
				sForm.forEach((item) => {
					let keys = Object.keys(userData);
					let values = Object.values(userData);

					keys.forEach((items, idx) => {
						if (item.name === items) {
							// console.log(item)
							item.value = values[idx]; //特殊表单赋值
						}
					});
				});
				return {
					newForm: form,
				};
			},
			async submit() {
				//提交
				this.$refs.codeForm.validate(async (valid) => {
					if (valid) {
						let newFormData = this.publicForm.concat(this.specialForm)//合并公共和特殊表单
						this.formData.form = JSON.stringify(newFormData)
						
						let newObj = this.getPublicForm(this.publicForm)
						let updateRes = await this.API_update(newObj)//更新用户信息
						this.UPDATE_USER_INFO(newObj)
						
						let data = Object.assign({},this.formData, this.detailsData,newObj)
						delete data.id

						// console.log(this.publicForm)
						
						let res = await this.API_save(data)//保存

						if (res.data.code === 1000 && updateRes.data.code === 1000) {
							this.$refs.uToast.show({
								title: res.data.msg,
								type: 'success',
								url: '/pages/signup/signup',
								isTab: true
							})
						} else {
							this.$refs.uToast.show({
								title: res.data.msg,
								type: 'error',
							})
						}

						this.codeShow = false
					} else {
						console.log("验证不通过")
						this.codeShow = false
					}
				})
			},
			getPublicForm(arr){
				let obj = {}
				arr.forEach((item)=>{
					obj[item.name] = item.value
				})
				
				let newObj = Object.assign({},this.userData,obj)
				return newObj
			},
			aFn(arr) { //公共表单过滤显示
				if (arr) {
					return arr.filter((item) => {
						return item.ispublic === 1
					})
				}
			},
			bFn(arr) { //特别表单过滤显示
				if (arr) {
					let newArr = arr.filter((item) => {
						return item.ispublic === 0
					})
					return newArr
				}
			},
			cFn(arr) { //如果没有动态，不显示
				if (arr) {
					return arr.some((item) => {
						return item.ispublic === 0
					})
				}
			},
			changeDayPublic(e, idx) { //公共日期选择
				this.publicForm[idx].value = e.year + "-" + e.month + "-" + e.day
			},
			checkboxGroupChangePublic(e, idx) { //多选
				this.publicForm[idx].value = e
			},
			showSelectPublic(idx) { //显示下拉列表选择器
				this.publicForm[idx].isShow = true
			},
			confirmPublic(e, idx) { //列选择
				this.publicForm[idx].label = e[0].label
				this.publicForm[idx].value = e[0].value
			},
			async onListChange(lists,item,idx){
				
				if (lists.length) {
					let res = await getBase64(lists[0].url) //base64转码

					this.publicForm[idx].value = res
					this.$refs[item.id][0].lists = [{
						url: res
					}]
				}
			},
			beforeRemove(index,lists){
				console.log(index)
				console.log(lists)
			},
			showDatePickerPublic(idx) { //特殊日期选择器
				this.publicForm[idx].isShow = true
			},
			changeDay(e, idx) { //日期选择
				// this.specialForm[idx].value = e.result
				this.specialForm[idx].value = e.year + "-" + e.month + "-" + e.day
			},
			checkboxGroupChange(e, idx) { //多选
				this.specialForm[idx].value = e
			},
			showSelect(idx) { //显示下拉列表选择器
				this.specialForm[idx].isShow = true
			},
			confirm(e, idx) { //列选择
				this.specialForm[idx].label = e[0].label
				this.specialForm[idx].value = e[0].value
			},
			showDatePicker(idx) { //日期选择器
				this.specialForm[idx].isShow = true
				console.log(this.specialForm[idx])
			},
			newFormFilter(arr) {
				arr.forEach(function(item) {
					if (item.type === 4) {
						item.optn.forEach((items) => {
							if (items.value === item.value) {
								item.label = items.key
							}
						})
					}
				})
				return arr
			},
			codeShowFn() {

				let arr = [];
				this.publicForm.map((item) => {
					if (item.crer && (!item.value || item.value === "" || (item.value instanceof Array && !item.value.length))) {
						//没有值或者为空字符串或者长度为0
						arr.push(item.ndsib);
					}
				});
				this.specialForm.map((item) => {
					if (!item.crer && (!item.value || item.value === "" || (item.value instanceof Array && !item.value.length))) {
						//没有值或者为空字符串或者长度为0
						arr.push(item.ndsib);
					}
				});


				this.errorArr = arr;

				if (this.errorArr.length) {
					//没有填写完毕
					this.dialogVisible = true;
				} else {
					this.codeShow = true
				}
			},
			async API_signupCaptcha() {
				let result = {

				}
				return await signupCaptcha(result)
			},
			setIntervalHandler() {
				this.timeHandler = setInterval(() => {
					if (this.time > 0) {
						this.time--
						this.timeHandlerBool = false
					} else {
						clearInterval(this.timeHandler)
						this.timeHandlerBool = true
						this.time = 60
					}
				}, 1000)
			},
			async sendCode() { //发送验证码
				this.setIntervalHandler()

				let res = await this.API_signupCaptcha()
				if (res.data.code === 1000) {
					this.$refs.uToast.show({
						title: res.data.msg,
						type: 'success',
					})
				} else {
					this.$refs.uToast.show({
						title: res.data.msg,
						type: 'error',
					})
				}
			},
		},
		async onLoad(option) {
			this.$refs.loading.showLoading()
			this.detailsData = JSON.parse(this.$store.state.signUpForm.row) //获取考试详细数据

			// console.log(this.detailsData)
			// console.log(option)
			let formRes = await this.API_getFrom(option.eid); //获取动态表单

			this.formData = formRes.data.data

			if (!this.formData) {

				this.$refs.uToast.show({
					title: '没有报名表单数据，请在后台添加后再查看。',
					type: 'error',
					url: '/pages/home/home',
					isTab: true
				})
			}


			let formData = this.formOptn(JSON.parse(formRes.data.data.form)); //格式化选项

			let userRes = await this.API_getExaminee(); //获取公共表单
			this.userData = userRes.data.data;
			console.log(this.userData)


			let {
				newForm
			} = this.filter(formData, this.userData); //特殊表单和公共表单做对比

			this.form = this.newFormFilter(newForm);

			this.publicForm = this.aFn(this.form) //公共表单
			this.specialForm = this.bFn(this.form) //特殊表单

			console.log(this.publicForm)

			this.$refs.loading.hideLoading()
		},
		onReady() {
			this.$refs.codeForm.setRules(this.codeFormRules);
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		padding: 0 20rpx;
		box-sizing: border-box;
	}
</style>
